package com.glw.sso.platform.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.glw.sso.platform.common.constant.CacheKeyEnum;
import com.glw.sso.platform.common.exception.BusinessException;
import com.glw.sso.platform.common.exception.SystemException;
import com.glw.sso.platform.common.util.Assert;
import com.glw.sso.platform.common.util.LoginContext;
import com.glw.sso.platform.common.util.LoginInfo;
import com.glw.sso.platform.common.util.SHA1;
import com.glw.sso.platform.domain.entity.User;
import com.glw.sso.platform.domain.mapper.UserMapper;
import com.glw.sso.platform.domain.vo.MenuTreeVO;
import com.glw.sso.platform.service.MenuService;
import com.glw.sso.platform.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    RedisTemplate<String, Object> redisTemplate;

    @Value("${login.expire}")
    private Integer loginExpireTime;

    @Autowired
    private MenuService menuService;

    @Override
    public String login(String username, String password) {
        password = SHA1.encryption(password);
        User user = super.lambdaQuery().eq(User::getUsername, username).eq(User::getPassword, password).one();
        Assert.notNull(user, BusinessException.Code.LOGIN_FAIL, username);

        String ticket = UUID.randomUUID().toString();
        String key = CacheKeyEnum.UserInfoStringCache.key(ticket);
        redisTemplate.opsForValue().set(key, user, loginExpireTime, TimeUnit.MINUTES);
        log.info("登录成功 {}|{}", user.getUsername(), key);
        return ticket;
    }

    @Override
    public User getLoginUserInfo(String token) {
        String key = CacheKeyEnum.UserInfoStringCache.key(token);
        Object o = redisTemplate.opsForValue().get(key);
        Assert.notNull(o, SystemException.Code.UN_LOGIN);
        return (User) o;
    }

    @Override
    public String loginOther(String username) {


        return null;
    }

    @Override
    public Boolean logout() {
        LoginInfo currentLoginUser = LoginContext.getCurrentLoginUser();
        if (currentLoginUser != null) {
            log.info("用户退出登录{}", currentLoginUser);
            String key = CacheKeyEnum.UserInfoStringCache.key(currentLoginUser.getToken());
            return redisTemplate.delete(key);
        }
        return false;
    }

    @Override
    public List<MenuTreeVO> getMenuTree(String appId) {
        return menuService.getUserMenuTree(LoginContext.getCurrentLoginUser().getPin(), appId);
    }
}
